package tcpServerAndClient;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.ProcessBuilder.Redirect;
import java.net.ServerSocket;
import java.net.Socket;

import cmdParser.CmdParser;

public class TcpServer {
	public static void main(String[] args) throws IOException {
		OutputStream out = null;
		InputStream in = null;
		BufferedReader reader = null;
		String PATH = "filePool/";
		ServerSocket server = new ServerSocket(8001);    //a exception may throw
		
		Socket socket = null;
		String request = null;
		String filename = null;
		
		boolean status = true;
		while(status){
			socket = server.accept();					//每次重新开一个socket,监听不同的客户端
			out = socket.getOutputStream();
			in = socket.getInputStream();
			reader = new BufferedReader(new InputStreamReader(in));			//装饰类
			
			request = reader.readLine();				//接收请求： 如scp test.txt
			
			String[] params = CmdParser.cmdParseForServer(request);            //this request is null
			
			if(params != null){
				if(params[0].equals("LS")){
					//这里是LS命令
					File file = new File(PATH);
					File[] files = file.listFiles();
					String fileList = "";
					for(File f:files){
						fileList += f.getName() + " ";
					}
					
					System.out.println(fileList + "filelist");
					//传回去客户端
					out.write((fileList + "\n").getBytes() );
				}
				else{
					if(params[0].equals("SCP")){
						//SCP命令
						filename = params[1];
						if(filename != null){					//当文件名合法
							out.write("ack\n".getBytes());
							File file = new File(PATH + filename.substring(1));
							
							byte[] buf = new byte[1];
							int len = 0;
							FileOutputStream out1 = new FileOutputStream(file);
							//读网络,拷贝文件
							while((len = in.read(buf)) != -1){				//阻塞在这里
								out1.write(buf);
							}
							System.out.println("接收文件成功");
							out1.close();
						}
						
					}else{		
						//RM命令
						filename = params[1];
						
						File file = new File(PATH+ filename);
						if(file.exists()){
							file.delete();
						}
						else{
							out.write("file is not exist\n".getBytes());
						}
						out.write("delete file finish\n".getBytes());
					}
				}
			}
		}
		out.close();
		in.close();
		reader.close();
		socket.close();
	}
	
}
